package com.springboot.cloud.sysadmin.organization.datapermission;

import com.springboot.cloud.common.core.annotation.DataScope;
import com.springboot.cloud.common.core.utils.StringUtils;
import com.springboot.cloud.common.web.entity.po.BasePo;
import com.springboot.cloud.sysadmin.organization.config.MyMetaObjectHandler;
import com.springboot.cloud.sysadmin.organization.entity.po.Role;
import com.springboot.cloud.sysadmin.organization.entity.po.User;
import com.springboot.cloud.sysadmin.organization.service.impl.RoleService;
import com.springboot.cloud.sysadmin.organization.service.impl.UserService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by ZengJian on 2021/2/3 0003 上午 9:22
 * 数据过滤处理
 */
@Aspect
@Component
public class DataScopeAspect {
    @Autowired
    private UserService userService;

    @Autowired
    public RoleService roleService;

    /**
     * 全部数据权限
     */
    public static final String DATA_SCOPE_ALL = "1";

    /**
     * 自定数据权限
     */
    public static final String DATA_SCOPE_CUSTOM = "2";

    /**
     * 部门数据权限
     */
    public static final String DATA_SCOPE_DEPT = "3";

    /**
     * 部门及以下数据权限
     */
    public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

    /**
     * 仅本人数据权限
     */
    public static final String DATA_SCOPE_SELF = "5";

    /**
     * 数据权限过滤关键字
     */
    public static final String DATA_SCOPE = "dataScope";

    // 配置织入点
    @Pointcut("@annotation(com.springboot.cloud.common.core.annotation.DataScope)")
    public void dataScopePointCut() {
    }

    @Before("dataScopePointCut()")
    public void doBefore(JoinPoint point) throws Throwable {
        handleDataScope(point);
    }

    protected void handleDataScope(final JoinPoint joinPoint) {
        // 获得注解
        DataScope controllerDataScope = getAnnotationLog(joinPoint);
        if (controllerDataScope == null) {
            return;
        }
        String username = getUsername();
        if (StringUtils.isNotNull(username)) {
            User user = userService.getUserByUniqueId(username);
            // 如果是超级管理员，则不过滤数据
            if (StringUtils.isNotNull(user)) {
                dataScopeFilter(joinPoint, user, controllerDataScope.deptAlias(),
                        controllerDataScope.userAlias());
            }
        }
    }

    /**
     * 数据范围过滤
     *
     * @param joinPoint 切点
     * @param user      用户
     * @param userAlias 别名
     */
    public void dataScopeFilter(JoinPoint joinPoint, User user, String deptAlias, String userAlias) {
        System.out.println("user:" + user);
        StringBuilder sqlString = new StringBuilder();
        System.out.println("sqlString:" + sqlString);
        for (String code : user.getRoles()) {
            System.out.println("user.getRoles():" + user.getRoles());
            System.out.println("code:" + code);
            Role role1 = roleService.getRoleByCode(code);
            System.out.println("role1:" + role1);
            String dataScope = role1.getDataScope();
            System.out.println("dataScope:" + dataScope);
            if (DATA_SCOPE_ALL.equals(dataScope)) {
                sqlString = new StringBuilder();
                break;
            } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) {
                System.out.println("user_id:" + user.getId());
                sqlString.append(StringUtils.format(
                        " and {}.dept_id IN ( SELECT dept_id FROM role_dept_relation WHERE role_id in " +
                                "(select role_id from user_role_relation where user_id={})  ) ", deptAlias,
                        user.getId()));
            } else if (DATA_SCOPE_DEPT.equals(dataScope)) {
                sqlString.append(StringUtils.format(" and {}.dept_id in (select dept_id from user_dept_relation where user_id={}) ", deptAlias, user.getId()));
            } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) {
                sqlString.append(StringUtils.format(
                        " and {}.dept_id IN ( SELECT id FROM dept WHERE id in (select dept_id from user_dept_relation where user_id={})  )",
                        deptAlias, user.getId()));
            } else if (DATA_SCOPE_SELF.equals(dataScope)) {
                if (StringUtils.isNotBlank(userAlias)) {
                    sqlString.append(StringUtils.format(" and {}.id = {} ", userAlias, user.getId()));
                } else {
                    // 数据权限为仅本人且没有userAlias别名不查询任何数据
                    sqlString.append(" and 1=0 ");
                }
            }
        }
        System.out.println("sqlString.toString():" + sqlString.toString());
        if (StringUtils.isNotBlank(sqlString.toString())) {
            System.out.println("sqlString.toStrings():" + sqlString.toString());
//            Object params = joinPoint.getArgs()[0];
            BasePo params = (BasePo) joinPoint.getArgs()[0];
            if (StringUtils.isNotNull(params) && params instanceof BasePo) {
                BasePo basePo = (BasePo) params;
                System.out.println("basePo:" + basePo);
                basePo.getParams().put(DATA_SCOPE, sqlString.toString());
            }

        }

    }

    /**
     * 是否存在注解，如果存在就获取
     */
    private DataScope getAnnotationLog(JoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();

        if (method != null) {
            return method.getAnnotation(DataScope.class);
        }
        return null;
    }

    public String getUsername() {
        MyMetaObjectHandler myMetaObjectHandler = new MyMetaObjectHandler();
        return myMetaObjectHandler.getCurrentUsername();
    }
}
